package xin.ryven.car.android

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import xin.ryven.car.android.databinding.ActivityMainBinding
import java.io.File

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val STORAGE_PERMISSION_CODE = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        checkPermissionsAndStart()
    }

    private fun checkPermissionsAndStart() {
        // 检查基本存储权限
        if (hasStoragePermission()) {
            initializeMusicDirectory()
            startPlayerActivity()
        } else {
            requestStoragePermission()
        }
    }

    private fun initializeMusicDirectory() {
        try {
            // 获取外部存储目录
            val externalDir = getExternalFilesDir(null)
            Log.d("MainActivity", "External directory: ${externalDir?.absolutePath}")

            // 创建音乐根目录
            val musicDir = File(externalDir, "music")
            if (!musicDir.exists()) {
                val created = musicDir.mkdirs()
                Log.d("MainActivity", "Created music directory: $created")
            }

            // 创建默认歌单目录
            val defaultPlaylist = File(musicDir, "默认歌单")
            if (!defaultPlaylist.exists()) {
                val created = defaultPlaylist.mkdirs()
                Log.d("MainActivity", "Created default playlist directory: $created")
            }

            // 检查目录是否可写
            if (!defaultPlaylist.canWrite()) {
                Log.e("MainActivity", "Default playlist directory is not writable")
                Toast.makeText(this, "无法写入歌单目录", Toast.LENGTH_LONG).show()
                return
            }

            // 直接启动 PlayerActivity，不需要检查文件
            startPlayerActivity()
            
        } catch (e: Exception) {
            Log.e("MainActivity", "Error in initializeMusicDirectory", e)
            Toast.makeText(this, "初始化音乐目录失败: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }

    private fun hasStoragePermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.READ_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED &&
        ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun requestStoragePermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ),
            STORAGE_PERMISSION_CODE
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == STORAGE_PERMISSION_CODE) {
            if (grantResults.isNotEmpty() && 
                grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                initializeMusicDirectory()
                startPlayerActivity()
            } else {
                Toast.makeText(this, "需要存储权限才能播放音乐", Toast.LENGTH_LONG).show()
                finish()
            }
        }
    }

    private fun startPlayerActivity() {
        val intent = Intent(this, PlayerActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
        }
        startActivity(intent)
        finish()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == STORAGE_PERMISSION_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    initializeMusicDirectory()
                    startPlayerActivity()
                } else {
                    Toast.makeText(this, "需要存储权限才能播放音乐", Toast.LENGTH_LONG).show()
                    finish()
                }
            }
        }
    }

    private fun checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11 及以上版本
            try {
                if (!Environment.isExternalStorageManager()) {
                    val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
                    startActivity(intent)
                }
            } catch (e: NoSuchMethodError) {
                // 如果方法不存在，退回到传统的权限请求
                requestLegacyStoragePermission()
            }
        } else {
            // Android 10 及以下版本
            requestLegacyStoragePermission()
        }
    }

    private fun requestLegacyStoragePermission() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ),
                STORAGE_PERMISSION_CODE
            )
        }
    }

    override fun onBackPressed() {
        moveTaskToBack(true)
    }

    companion object {
        private const val STORAGE_PERMISSION_CODE = 1001
    }
}